package com.cz.kingdee.prod;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.cz.kingdee.KingdeeClient;
import com.cz.kingdee.dto.*;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.sdk.K3CloudApi;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 根据生产入库单，下发生产汇报单
 */
public class PuChangMoPrdByStock {
    public static void main(String[] args) throws Exception {
        KingdeeClient client = new KingdeeClient();
        //K3CloudApi k3CloudApi = client.getTestKingdeeClient();
        K3CloudApi k3CloudApi = client.getProdKingdeeClient();
        String dbGroup = "mes-prod-slave";
        List<String> errorList = new ArrayList<>();
        Set<String> newBillNoSet = new HashSet<>();
        List<String> codes = new ArrayList<>();

        codes.add("SCRKCZ25134922");

        for(String billNo: codes){
            QueryParam queryParam = new QueryParam();
            queryParam.setFormId("PRD_INSTOCK");
            queryParam.setFieldKeys("FMaterialId,FMaterialName,FBillNo,FDate,FMoBillNo,FMoId,FMoEntryId,FRealQty,F_ora_XSDDH,FMoEntrySeq,FMaterialId.FNumber,FApproveDate,FPrdOrgId.FName,FWorkShopId1.FName,FStockId.FName");
            queryParam.setFilterString("FBillNo='" + billNo + "'");
            List<PrdInstock> prdInstockList = k3CloudApi.executeBillQuery(queryParam, PrdInstock.class);
            /** 订单明细  **/
            int mocEntryId = prdInstockList.get(0).getFMoEntryId();


            /** 生产入库单  一个订单明细对应多个生产入库单 **/
            queryParam = new QueryParam();
            queryParam.setFormId("PRD_INSTOCK");
            queryParam.setFieldKeys("FMaterialId,FMaterialName,FBillNo,FDate,FMoBillNo,FMoId,FMoEntryId,FRealQty,F_ora_XSDDH,FMoEntrySeq,FMaterialId.FNumber,FApproveDate,FPrdOrgId.FName,FWorkShopId1.FName,FStockId.FName");
            queryParam.setFilterString("FMoEntryId=" + mocEntryId +  " ");
            prdInstockList = k3CloudApi.executeBillQuery(queryParam, PrdInstock.class);
            for(PrdInstock prdInstock: prdInstockList){
                newBillNoSet.add(prdInstock.getFBillNo());
            }
        }

        List<Map<String,Object>> dataMapList = new ArrayList<>();
        int i = 0;
        for (String FBillNo : newBillNoSet) {
            System.out.println("当前处理第"+i+++"条数据");
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("入库单号", FBillNo);

            /** 获取生产入库单  **/
            QueryParam queryParam = new QueryParam();
            queryParam.setFormId("PRD_INSTOCK");
            queryParam.setFieldKeys("FMaterialId,FMaterialName,FBillNo,FDate,FMoBillNo,FMoId,FMoEntryId,FRealQty,F_ora_XSDDH,FMoEntrySeq,FMaterialId.FNumber,FApproveDate,FPrdOrgId.FName,FWorkShopId1.FName,FStockId.FName");
            queryParam.setFilterString("FBillNo='" + FBillNo + "'");
            List<PrdInstock> prdInstockList = k3CloudApi.executeBillQuery(queryParam, PrdInstock.class);


            String date = "2025-01-31 00:00:00";
            int mocEntryId = prdInstockList.get(0).getFMoEntryId();

            /** 查询生产用料清单  **/
            QueryParam materialQueryParam = new QueryParam();
            materialQueryParam.setFormId("PRD_PPBOM");
            materialQueryParam.setFieldKeys("FBillNo");
            materialQueryParam.setFilterString("FMOEntryID =" + mocEntryId);
            List<PrdPpbom> prdPpbomList = k3CloudApi.executeBillQuery(materialQueryParam, PrdPpbom.class);
            String pBom = prdPpbomList.get(0).getFBillNo();

            if (StrUtil.isEmpty(pBom)) {
                errorList.add("生产入库单:" + FBillNo + "没有对应的生产用料清单");
                dataMap.put("失败原因","没有对应的生产用料清单");
                dataMapList.add(dataMap);
                continue;
            }
            System.out.println("物料编码：" + pBom);
            if (pBom.endsWith("-1")) {
                pBom = pBom.substring(0, pBom.length() - 2);
            }


            /** 下推  **/
            PushPrdMorpt pushPrdMorpt = new PushPrdMorpt();
            pushPrdMorpt.setEntryIds(String.valueOf(mocEntryId));
            pushPrdMorpt.setTargetFormId("PRD_MORPT");
            pushPrdMorpt.setIsEnableDefaultRule(true);
            String params = JSONUtil.toJsonStr(pushPrdMorpt);
            System.out.println("请求参数：" + params);
            String result = k3CloudApi.push("PRD_MO", params);
            System.out.println(result);
            ResultWrapper resultWrapper = JSONUtil.toBean(result, ResultWrapper.class);
            if (!resultWrapper.getResult().getResponseStatus().isIsSuccess()) {
                errorList.add("生产入库单:" + FBillNo + "下推失败" + JSONUtil.toJsonStr(resultWrapper.getResult().getResponseStatus().getErrors()));
                dataMap.put("失败原因", JSONUtil.toJsonStr(resultWrapper.getResult().getResponseStatus().getErrors()));
                dataMapList.add(dataMap);
                continue;
            }
            int id = resultWrapper.getResult()
                    .getResponseStatus()
                    .getSuccessEntitys()
                    .get(0)
                    .getId();

            int fEntityId = resultWrapper.getResult()
                    .getResponseStatus()
                    .getSuccessEntitys()
                    .get(0)
                    .getEntryIds()
                    .getFEntity().get(0);


            int totalQuantity = prdInstockList.stream().mapToInt(PrdInstock::getFRealQty).sum();

            String sql = " select abc.*,\n" +
                    "               tp.to_make_num                                 as jiaGongCount,\n" +
                    "               tp.only_code,\n" +
                    "               if(LEFT(tp.moc_no,4) = 'MOCZ',tp.moc_no, null) as production_order,\n" +
                    "               product_no,\n" +
                    "               tp.create_on,\n" +
                    "               p_bom_no\n" +
                    "        from (select SUM(CAST(total_time-prep_time as DECIMAL(12, 2)))                         as totalTime,\n" +
                    "                     ROUND(SUM(CAST(total_time-prep_time as DECIMAL(12, 2))) / process_num, 2) as singleJiaGongCount,\n" +
                    "                     technological_process_id\n" +
                    "              from operation_procedure\n" +
                    "              GROUP BY technological_process_id) as abc\n" +
                    "                 left join technological_process tp on abc.technological_process_id = tp.id\n" +
                    "        where tp.p_bom_no  = :p_bom_no \n" +
                    "          and tp.`status` = 1";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("p_bom_no", pBom);

            Entity timeEntity = Db.use(dbGroup).queryOne(sql, paramMap);
            if (timeEntity == null) {
                errorList.add("生产入库单:" + FBillNo + "在mes中没有找到对应的工艺路线");
                dataMap.put("失败原因", "在mes中没有找到对应的工艺路线");
                dataMapList.add(dataMap);
                continue;
            }
            BigDecimal totalTime = timeEntity.getBigDecimal("totalTime");
            BigDecimal jiaGongCount = timeEntity.getBigDecimal("jiaGongCount");
            BigDecimal time = totalTime.multiply(new BigDecimal(totalQuantity).divide(new BigDecimal(60), 8, RoundingMode.DOWN).divide(jiaGongCount, 3, RoundingMode.DOWN));


            /** 修改生产汇报单子  **/
            PrdMorptSaveRequest request = new PrdMorptSaveRequest();
            request.setIsDeleteEntry(false);

            PrdMorptSaveRequest.Model model = new PrdMorptSaveRequest.Model();
            model.setFID(id);
            model.setFDate(date);

            List<PrdMorptSaveRequest.FEntity> entities = new ArrayList<>();
            PrdMorptSaveRequest.FEntity entity = new PrdMorptSaveRequest.FEntity();
            System.out.println(totalQuantity);
            entity.setFEntryID(fEntityId);
            entity.setFQuaQty(totalQuantity);
            entity.setFFinishQty(totalQuantity);
            entity.setFHrWorkTime(time);
            entities.add(entity);
            model.setFEntity(entities);

            request.setModel(model);

            String requestJson = JSONUtil.toJsonStr(request);
            System.out.println("请求参数22222：" + requestJson);
            String saveResult = k3CloudApi.save("PRD_MORPT", JSONUtil.toJsonStr(requestJson));
            System.out.println("保存结果22222：" + saveResult);

        }

        if(CollUtil.isNotEmpty(dataMapList)){
            ExcelWriter writer = ExcelUtil.getWriter();

            // 写数据到 Excel
            writer.write(dataMapList, true); // true 表示写入标题行


            File outFile = new File("D://output"+ RandomUtil.randomNumbers(20)+".xlsx");
            // 设置文件输出路径
            writer.flush(outFile);

            // 关闭写入器
            writer.close();

        }

        if (CollUtil.isNotEmpty(errorList)) {
            File file = new File("D:/PuChangMoPrdByStock.txt");
            FileUtil.writeLines(errorList, file, "utf-8");
        }


    }

}
